import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { EyeOutlined } from "@ant-design/icons";
import { useRequest } from "ahooks";
import type { TableColumnsType, TableProps } from "antd";
import { Badge, Button, Flex, Switch, Tooltip } from "antd";
import dayjs from "dayjs";
import SearchForm from "@/components/search-form";
import Table from "@/components/table";
import CreateButton from "./components/create-button";
import EditButton from "./components/edit-button";
import StatusModal from "./components/status-modal";
import { updateOrder, useOrderList } from "@/api/order";
import { ROUTE_PATHS } from "@/constants/common";
import {
  ORDER_CONTENT_CATEGORY_OPTIONS,
  ORDER_CONTENT_TYPE_OPTIONS,
  ORDER_STATUS_OPTIONS,
} from "@/constants/options";

import { OrderDataType } from "@/types/order";

type TableRowSelection<T extends object = object> = TableProps<T>["rowSelection"];

export default function OrderManagement() {
  const [queryParams, setQueryParams] = useState({
    pageNum: 1,
    pageSize: 10,
  });

  const { data, loading: isFetching, runAsync: fetchList, refresh } = useOrderList();

  const { run: runUpdateOrder, loading: isUpdating } = useRequest(
    async (id: number, updateData: Partial<OrderDataType>) => {
      return updateOrder(id, updateData);
    },
    {
      manual: true,
      onSuccess: (data: { businessOrder: OrderDataType }) => {
        window.$message?.success(`${data.businessOrder.isVisible ? "开启" : "关闭"}成功`);
        refresh();
      },
      onError: () => {
        window.$message?.error("更新失败");
        refresh();
      },
    },
  );

  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: [5, 10, 20, 50],
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [openStatusModal, setOpenStatusModal] = useState(false);
  const [statusData, setStatusData] = useState<OrderDataType | OrderDataType[] | null>(null);

  const [modalConfig, setModalConfig] = useState<{
    type: "confirm" | "error" | "info";
    title?: string;
    content?: string;
  }>({ type: "confirm" });

  const columns: TableColumnsType<OrderDataType> = [
    {
      title: "商单ID",
      dataIndex: "id",
      key: "id",
      width: 80,
    },
    {
      title: "合作品牌",
      dataIndex: "brand",
      key: "brand",
      width: 120,
      ellipsis: true,
      render: (_, record) => <Tooltip title={record.brand}>{record.brand}</Tooltip>,
    },
    {
      title: "商单标题",
      dataIndex: "title",
      key: "title",
      width: 200,
      ellipsis: true,
      render: (_, record) => (
        <Tooltip title={record.title} placement="topLeft">
          {record.title}
        </Tooltip>
      ),
    },
    {
      title: "内容领域",
      dataIndex: "contentCategory",
      key: "contentCategory",
      width: 100,
    },
    {
      title: "合作类型",
      dataIndex: "contentType",
      key: "contentType",
      width: 100,
      render: (_, record) =>
        ORDER_CONTENT_TYPE_OPTIONS.find((option) => option.value === record.contentType)?.label,
    },
    {
      title: "达人需求",
      dataIndex: "influencerCount",
      key: "influencerCount",
      width: 100,
    },
    {
      title: "已报名",
      dataIndex: "createdAt",
      key: "createdAt",
      width: 80,
      render: () => "-",
    },
    {
      title: "已入选",
      dataIndex: "lastLoginAt",
      key: "lastLoginAt",
      width: 80,
      render: () => "-",
    },
    {
      title: "商单状态",
      dataIndex: "isVisible",
      key: "isVisible",
      width: 100,
      render: (_, record) => (
        <Badge
          color={record.isVisible ? "green" : "red"}
          text={ORDER_STATUS_OPTIONS.find((option) => option.value === record.isVisible)?.label}
        />
      ),
    },
    {
      title: "创建时间",
      dataIndex: "status",
      key: "status",
      width: 120,
      render: (_, record) => dayjs(record.createdAt).format("YYYY-MM-DD"),
    },
    {
      title: "发布时间",
      dataIndex: "status",
      key: "status",
      width: 120,
      render: (_, record) => dayjs(record.createdAt).format("YYYY-MM-DD"),
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      fixed: "right",
      width: 120,
      render: (_, record) => {
        return (
          <Flex justify="end" gap={8}>
            <Tooltip title="查看详情">
              <Link to={`${ROUTE_PATHS.orderDetail.replace(":id", record.id.toString())}`}>
                <Button type="link" size="middle" icon={<EyeOutlined />} />
              </Link>
            </Tooltip>
            <EditButton data={record} refresh={refresh} />
            <Tooltip title={record.isVisible ? "状态关闭" : "状态开启"}>
              <Flex align="center">
                <Switch
                  size="small"
                  checked={record.isVisible}
                  loading={isUpdating}
                  onChange={() => {
                    // 如果有多选，清空多选，只处理单条数据
                    if (selectedRowKeys.length > 0) {
                      setSelectedRowKeys([]);
                    }
                    setStatusData(record);
                    setModalConfig({ type: "confirm" });
                    setOpenStatusModal(true);
                  }}
                />
              </Flex>
            </Tooltip>
          </Flex>
        );
      },
    },
  ];

  const canHideColumns: TableColumnsType<OrderDataType> = [
    {
      title: "商单ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "商单标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "内容领域",
      dataIndex: "contentCategory",
      key: "contentCategory",
    },
    {
      title: "合作类型",
      dataIndex: "contentType",
      key: "contentType",
    },
    {
      title: "达人需求",
      dataIndex: "influencerCount",
      key: "influencerCount",
    },
  ];

  const schema = [
    {
      name: "businessOrderId",
      label: "商单ID",
      type: "input",
      componentProps: { placeholder: "请输入" },
    },
    {
      name: "brand",
      label: "合作品牌",
      type: "input",
      componentProps: { placeholder: "请输入" },
    },
    {
      name: "contentCategory",
      label: "内容领域",
      type: "select",
      componentProps: {
        placeholder: "请选择或输入",
        options: ORDER_CONTENT_CATEGORY_OPTIONS,
        showSearch: true,
      },
    },
    {
      name: "xhsAccount",
      label: "合作类型",
      type: "select",
      componentProps: {
        placeholder: "请选择",
        options: ORDER_CONTENT_TYPE_OPTIONS,
      },
    },
    {
      name: "",
      label: "粉丝要求",
      type: "rangeInput",
      componentProps: {
        start: { name: "fansMin", placeholder: "不小于" },
        end: { name: "fansMax", placeholder: "不大于" },
      },
    },
    {
      name: "isVisible",
      label: "商单状态",
      type: "select",
      componentProps: {
        options: [
          { label: "正常", value: 1 },
          { label: "禁用", value: 0 },
        ],
      },
    },
    {
      name: "createdAt",
      label: "发布时间",
      type: "rangePicker",
      componentProps: {
        id: { start: "cooperationStartGte", end: "cooperationEndLte" },
        format: "YYYY-MM-DD",
      },
    },
  ];

  const onSearch = (values: any) => {
    console.log("搜索参数: ", values);
    const newParams = {
      ...values,
      pageNum: 1, // 搜索时重置为第一页
      pageSize: pagination.pageSize,
    };
    setQueryParams(newParams);
    setPagination({ ...pagination, current: 1 });

    // 手动触发查询
    fetchList(newParams);
  };

  const onPageChange = (page: number, pageSize: number) => {
    const newParams = {
      ...queryParams,
      pageNum: page,
      pageSize: pageSize,
    };

    setQueryParams(newParams);
    setPagination({
      ...pagination,
      current: page,
      pageSize: pageSize,
    });

    // 手动触发查询
    fetchList(newParams);
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection: TableRowSelection<OrderDataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handleRefresh = () => {
    refresh();
  };

  const handleBatchStatusChange = (targetStatus: boolean) => {
    if (selectedRowKeys.length === 0) {
      return;
    }

    // 获取选中的商单数据
    const selectedOrders =
      data?.businessOrders?.filter((order: OrderDataType) => selectedRowKeys.includes(order.id)) || [];

    if (selectedOrders.length === 0) {
      return;
    }

    // 检查状态是否一致
    const currentStatuses = selectedOrders.map((order: OrderDataType) => order.isVisible);
    const hasInconsistentStatus = currentStatuses.some((status: boolean) => status !== currentStatuses[0]);

    if (hasInconsistentStatus) {
      // 状态不一致，显示错误提示
      window.$message?.warning("选择的商单包含多个状态，需一致哦");
      setStatusData(null);
      return;
    }

    // 检查当前状态是否已经是目标状态
    const currentStatus = currentStatuses[0];
    if (currentStatus === targetStatus) {
      // 状态已经是目标状态
      const statusText = targetStatus ? "开启" : "关闭";
      window.$message?.info(`商单状态已${statusText}`);
      setStatusData(null);
      return;
    }

    // 状态一致且需要修改，显示确认弹窗
    const updatedOrders = selectedOrders.map((order: OrderDataType) => ({
      ...order,
      isVisible: targetStatus,
    }));

    setStatusData(updatedOrders);
    setModalConfig({ type: "confirm" });
    setOpenStatusModal(true);
  };

  const handleStatusConfirm = async () => {
    if (!statusData) return;
    if (Array.isArray(statusData)) {
      const results = await Promise.allSettled(
        statusData.map((item) => updateOrder(item.id, { isVisible: item.isVisible })),
      );
      const successCount = results.filter((result) => result.status === "fulfilled").length;
      const failCount = results.length - successCount;

      if (failCount === 0) {
        window.$message?.success("批量更新成功");
        setSelectedRowKeys([]); // 清空选择
      } else {
        window.$message?.error(`更新失败，成功${successCount}条，失败${failCount}条`);
      }

      // 统一刷新列表
      refresh();
    } else {
      // 单条更新 - 可以继续使用 runUpdateOrder
      await runUpdateOrder(statusData.id, { isVisible: !statusData.isVisible });
    }

    setOpenStatusModal(false);
    setStatusData(null);
  };

  useEffect(() => {
    fetchList(queryParams);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="flex flex-col h-full overflow-hidden">
      <div className="mb-4 bg-white rounded-lg p-4 dark:bg-[#1f1f1f] flex-shrink-0">
        <SearchForm schema={schema} onSearch={onSearch} />
      </div>
      <div className="bg-white rounded-lg p-4 dark:bg-[#1f1f1f] flex-1 flex flex-col overflow-hidden">
        <Table
          rowKey="id"
          columns={columns}
          canHideColumns={canHideColumns}
          dataSource={data?.businessOrders}
          loading={isFetching}
          pagination={{ ...pagination, total: Number(data?.total || 0) }}
          rowSelection={rowSelection}
          onPageChange={onPageChange}
          onRefresh={handleRefresh}
          leftActions={
            <>
              <CreateButton refresh={refresh} />
              <Button
                size="middle"
                type="primary"
                disabled={selectedRowKeys.length === 0}
                onClick={() => handleBatchStatusChange(true)}
              >
                开启
              </Button>
              <Button
                size="middle"
                type="primary"
                ghost
                disabled={selectedRowKeys.length === 0}
                onClick={() => handleBatchStatusChange(false)}
              >
                关闭
              </Button>
              {/* <Button size="middle" type="primary" ghost icon={<DownloadOutlined />}>
                导出
              </Button> */}
            </>
          }
        />
      </div>
      <StatusModal
        open={openStatusModal}
        data={statusData}
        onClose={() => {
          setOpenStatusModal(false);
          setStatusData(null);
        }}
        onConfirm={handleStatusConfirm}
        modalType={modalConfig.type}
        title={modalConfig.title}
        content={modalConfig.content}
      />
    </div>
  );
}
